package com.ruoyi.wisdom.controller;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.tool.TimerUtils;
//import com.ruoyi.faceplus.domain.UserFace;
//import com.ruoyi.faceplus.helper.FaceDetectHelper;
import com.ruoyi.wisdom.constants.IotConstants;
import com.ruoyi.wisdom.domain.IotConfig;
import com.ruoyi.wisdom.domain.IotPickDevice;
import com.ruoyi.wisdom.domain.activity.DetectSource;
import com.ruoyi.wisdom.domain.activity.HuaDevice;
import com.ruoyi.wisdom.helper.CameraPick;
import com.ruoyi.wisdom.service.IIotPickDeviceService;
import com.ruoyi.wisdom.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Calendar;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@RestController
public class CameraController extends BaseController {

    @Value("${arcpro.localPhotoPath}")
    private String localPhotoPath;

    @Value("${wisdom.isDetectList}")
    private boolean isDetectList;

    @Autowired
    @Qualifier("redisTemplate")
    public RedisTemplate redisTemplate;

    @Autowired
    private IIotPickDeviceService iotPickDeviceService;

    //@Autowired
    //private FaceDetectHelper faceDetectHelper;

    @Autowired
    private CameraPick cameraPick;

    /**
     * 不知名白色摄像头 【心跳检测】
     *
     * @param params
     * @return
     */
    @PutMapping("/DeviceEndianHeartbeat")
    public Map<String, Object> heartbeat(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new ConcurrentHashMap<>();
        // 更新在线状态
        IotPickDevice deviceParams = new IotPickDevice();
        deviceParams.setDeviceNo(params.get("SerialNum").toString());
        IotPickDevice deviceInfo = iotPickDeviceService.selectIotPickDevice(deviceParams);
        if (deviceInfo == null) {
            result.put("ReturnCode", 1);
        } else {
            deviceInfo.setOnline(1);
            deviceInfo.setOnlineTime(TimerUtils.getDateTime());
            iotPickDeviceService.updateIotPickDevice(deviceInfo);
            result.put("ReturnCode", 0);
        }
        return result;
    }

    /**
     * 不知名白色摄像头识别结果推送
     *
     * @param eventInfo
     * @param multipartFile
     * @return
     * @throws IOException
     */
    @PostMapping("/DeviceEndianEvent")
    public Map<String, Object> deviceEndianEvent(@RequestParam("EventInfo") MultipartFile eventInfo, @RequestParam("file") MultipartFile multipartFile) throws IOException {
        /*
        Map<String, Object> result = new ConcurrentHashMap<>();
        Object iotConfigObj = redisTemplate.opsForValue().get(IotConstants.SYSTEM_CONFIG);
        IotConfig iotConfig = JSON.parseObject(iotConfigObj.toString(), IotConfig.class);
        // 判断是否启用服务
        if (iotConfig != null && iotConfig.getEnableService() > 0) {
            String eventString = FileUtils.getContent(eventInfo.getInputStream(), StandardCharsets.UTF_8);
            JSONObject eventJson = JSONObject.parseObject(eventString);

            File file = multipartFormat(multipartFile);
            if (file != null) {
                // 统一人脸识别
                if (isDetectList) {
                    // 构造统一人脸数据数据格式
                    String filePath = file.getAbsolutePath();       // 获取图片完整路径
                    DetectSource detectData = DetectSource.builder()
                            .deviceNo(eventJson.getString("SerialNum"))
                            .filePath(filePath)
                            .faceTime(TimerUtils.getDateTime())
                            .build();
                    //缓存到队列里面 TASK_FACE_DETECT
                    redisTemplate.opsForList().rightPush(IotConstants.TASK_FACE_DETECT, JSONObject.toJSONString(detectData));
                } else {
                    // 构造统一人脸数据数据格式
                    DetectSource detectData = DetectSource.builder()
                            .deviceNo(eventJson.getString("SerialNum"))
                            .file(file)
                            .faceTime(TimerUtils.getDateTime())
                            .build();
                    UserFace userFace = faceDetectHelper.execute(detectData.getFile());
                    if (userFace != null) {
                        detectData.setUuid(Long.parseLong(userFace.getUserId()));
                        detectData.setFacecode(userFace.getFaceId());
                        detectData.setMask(userFace.getMask());
                        detectData.setSimilar(userFace.getSimilar());

                        // 获取当前是星期几，返回值是 1（星期日）到 7（星期六）的整数， 实际用法是0是星期天
                        Calendar calendar = Calendar.getInstance();
                        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
                        detectData.setWeek(Integer.toString(dayOfWeek));

                        // 逻辑处理：查询设备信息、人脸信息、场景信息
                        if (userFace.getUserGroup() == IotConstants.USER_GROUP_STUDENT){
                            detectData.setPersonType(IotConstants.USER_TYPE_STUDENT);
                            cameraPick.handleStudent(detectData);
                        }else if (userFace.getUserGroup() == IotConstants.USER_GROUP_TEACHER){
                            detectData.setPersonType(IotConstants.USER_TYPE_TEACHER);
                            cameraPick.handleTeacher(detectData);
                        }
                    }
                }
            }
        }
        result.put("ReturnCode", 0);
        return result;*/
        return null;
    }

    /**
     * 大华摄像头 【心跳状态】
     *
     * @param params
     */
    @PostMapping("/taskRequest")
    public void taskRequest(@RequestBody HuaDevice params) {
        System.out.println("大华摄像头 【心跳状态】");
        System.out.println(params);
        // 更新在线状态
        heartbeat(params.getDeviceId());
    }

    /**
     * 大华摄像头识别结果
     *
     * @param params
     */
    @PostMapping("/faceRecognition")
    public void faceRecognition(@RequestBody HuaDevice params) {
        /*
        System.out.println("大华摄像头识别结果");
        System.out.println(params.getDeviceId() + "--" + params.getFileName());
        Object iotConfigObj = redisTemplate.opsForValue().get(IotConstants.SYSTEM_CONFIG);
        IotConfig iotConfig = JSON.parseObject(iotConfigObj.toString(), IotConfig.class);
        // 判断是否启用服务
        if (iotConfig != null && iotConfig.getEnableService() > 0) {
            // 定义图片连接
            String filePath = localPhotoPath + File.separator + System.currentTimeMillis() + "output.jpg"; // 要保存的文件路径
            // 解码Base64字符串
            byte[] decodedBytes = Base64.getDecoder().decode(params.getImage());
            // 文件写入
            try (FileOutputStream fileOutputStream = new FileOutputStream(filePath)) {
                // 将字节写入文件
                fileOutputStream.write(decodedBytes);
                // 转换为File对象
                File file = new File(filePath);
                if (file != null) {
                    // 统一人脸识别
                    if (isDetectList) {
                        // 构造统一人脸数据数据格式
                        DetectSource detectData = DetectSource.builder().deviceNo(params.getDeviceId())
                                .filePath(filePath)
                                //.faceTime(TimerUtils.timeToDateTime(Long.valueOf(params.getSnapTimeMs())))
                                .faceTime(TimerUtils.getDateTime())
                                .build();
                        //缓存到队列里面 TASK_FACE_DETECT
                        redisTemplate.opsForList().rightPush(IotConstants.TASK_FACE_DETECT, JSONObject.toJSONString(detectData));
                    } else {
                        // 构造统一人脸数据数据格式
                        DetectSource detectData = DetectSource.builder().deviceNo(params.getDeviceId())
                                .file(file)
                                .photoBase64(params.getImage())
                                //.faceTime(TimerUtils.timeToDateTime(Long.valueOf(params.getSnapTimeMs())))
                                .faceTime(TimerUtils.getDateTime())
                                .build();
                        //faceDetectHelper.execute(detectData);
                        UserFace userFace = faceDetectHelper.execute(detectData.getFile());
                        if (userFace != null) {
                            // 逻辑处理：查询设备信息、人脸信息、场景信息


                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
         */
    }

    /**
     * 根据设备号设置设备在线时间 【心跳检测】
     *
     * @param deviceNo
     */
    private void heartbeat(String deviceNo) {
        if (StringUtils.isEmpty(deviceNo)) return;
        // 更新在线状态
        IotPickDevice deviceParams = new IotPickDevice();
        deviceParams.setDeviceNo(deviceNo);
        IotPickDevice deviceInfo = iotPickDeviceService.selectIotPickDevice(deviceParams);
        if (deviceInfo == null) return;
        deviceInfo.setOnline(1);
        deviceInfo.setOnlineTime(TimerUtils.getDateTime());
        iotPickDeviceService.updateIotPickDevice(deviceInfo);
    }

    /**
     * 图片上传
     *
     * @param file
     * @return
     */
    private String multipartUpload(MultipartFile file) {
        String filePath = "";
        // 上传简单文件名
        String originalFilename = file.getOriginalFilename();
        File localPath = new File(localPhotoPath);
        if (!localPath.exists()) localPath.mkdirs();
        // 存储路径
        filePath = localPhotoPath + File.separator + System.currentTimeMillis() + originalFilename;
        try {
            // 保存文件
            file.transferTo(new File(filePath));
            localPath.delete();
            localPath.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }

    /**
     * 文件上传
     *
     * @param multiFile
     * @return
     */
    private File multipartFormat(MultipartFile multiFile) {
        String fileName = multiFile.getOriginalFilename();
        if (fileName == null) return null;
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若须要防止生成的临时文件重复,能够在文件名后添加随机码
        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            System.out.println("~~~MultipartFile转File失败");
        }
        return null;
    }
}
